import React, {Component} from 'react';
import {
    StyleSheet,
    View,
    TextInput,
    Image,
    ListView,
    Text,
    TouchableHighlight,
    AsyncStorage,
    TouchableOpacity
} from 'react-native';
import {PullList} from 'react-native-pull';
import MainListItem from '../communals/MainListItem.js';
import HttpUtils from '../http/HttpUtils.js';
import {renderFooter} from './MyExports.js';
import {screenWidth} from './MyExports.js';
import NoDataView from './NoDataView.js';

/**
 * 商品搜索界面
 * Created by 10691 on 17/5/19.
 */
export default class Search extends Component {

    constructor() {
        super();
        this.state = {
            dataSource: new ListView.DataSource({rowHasChanged: (r1, r2) => r1 !== r2}),
            text: '',
            // 数据列表是否为空，为空时显示无数据的视图
            isNoData: true,
        };
        // 绑定操作
        this.loadData = this.loadData.bind(this);
        this.loadMore = this.loadMore.bind(this);
        this.renderRow = this.renderRow.bind(this);
    }

    componentDidMount() {
        this.loadData();
    }

    render() {
        return (
            <View style={SearchStyles.containerStyle}>
                <View style={SearchStyles.searchBarStyle}>
                    <View style={SearchStyles.searchFrameStyle}>
                        <Image source={{uri: 'search_icon_20x20'}} style={SearchStyles.searchImageStyle}/>
                        <TextInput
                            style={SearchStyles.textInputStyle}
                            keyboardType="default"
                            placeholder="请输入搜索商品关键字"
                            placeholderTextColor='gray'
                            autoFocus={true}
                            clearButtonMode="while-editing"
                            onChangeText={(text) => {
                                this.setState({text: text})
                            }}
                            onEndEditing={() => this.loadData()}
                            underlineColorAndroid={'transparent'}/>
                    </View>

                    {/* 取消 */}
                    <View style={{marginRight: 20}}>
                        <TouchableOpacity
                            onPress={() => {
                            }}>
                            <Text style={{color: 'green'}}>取消</Text>
                        </TouchableOpacity>
                    </View>
                </View>

                {this.renderList()}
            </View>
        );
    }

    /**
     * 网络请求加载数据
     * @param resolve
     */
    loadData(resolve) {
        if (!this.state.text) {
            return;
        }

        this.q=this.state.text;
        let params = {'q': this.q};
        HttpUtils.get('http://guangdiu.com/api/getresult.php', params).then((responseData) => {
            // 清空数据
            this.data = [];

            // 拼接数据
            this.data = this.data.concat(responseData.data);

            this.setState({dataSource: this.state.dataSource.cloneWithRows(this.data), isNoData: false});

            if (resolve !== undefined) {
                setTimeout(() => {
                    resolve()
                }, 1000);
            }

            // 存储数组中最后一个元素的id
            let searchLastID = responseData.data[responseData.data.length - 1].id;
            AsyncStorage.setItem('searchLastID', searchLastID.toString());

        }).catch((error) => {
            console.log(error)
        });
    }

    renderList() {
        if (this.state.isNoData) {
            return <NoDataView text={'请输入搜索商品并回车'}/>
        } else {
            return <PullList
                style={{width: screenWidth}}
                onPullRelease={(resolve) => this.loadData(resolve)}
                dataSource={this.state.dataSource}
                renderRow={this.renderRow}
                onEndReached={this.loadMore}
                onEndReachedThreshold={60}
                renderFooter={() => renderFooter()}/>
        }
    }

    /**
     * 返回每一个Item
     * @param rowData
     * @returns {XML}
     */
    renderRow(rowData) {
        return (
            <TouchableHighlight
                underlayColor={'#13fff0'}
                onPress={() => {
                    this.props.navigation.navigate('CommunalDetail', {ID: rowData.id});
                }}>
                <View>
                    <MainListItem
                        image={rowData.image}
                        title={rowData.title}
                        style={SearchStyles.listViewStyle}
                        mall={rowData.mall}
                        pubTime={rowData.pubtime}
                        fromSite={rowData.fromsite}/>
                </View>
            </TouchableHighlight>
        );
    }

    /**
     * 下拉加载更多
     */
    loadMore() {
        // 读取ID
        AsyncStorage.getItem('searchLastID').then((value) => {
            this.loadMoreData(value);
        });
    }

    /**
     * 加载更多数据
     */
    loadMoreData(value) {
        let params = {'q': this.q, 'sinceid': value};
        HttpUtils.get('http://guangdiu.com/api/getresult.php', params).then((responseData) => {

            // 拼接数据
            this.data = this.data.concat(responseData.data);
            this.setState({dataSource: this.state.dataSource.cloneWithRows(this.data)});

            let searchLastID = responseData.data[responseData.data.length - 1].id;
            AsyncStorage.setItem('searchLastID', searchLastID.toString());
        }).catch((error) => {
            console.log(error);
        });
    }

}

const SearchStyles = StyleSheet.create({

    containerStyle: {
        flex: 1,
        alignItems: 'center',
        backgroundColor: 'white',
    },

    // 顶部搜索栏
    searchBarStyle: {
        width: screenWidth,
        height: 45,
        flexDirection: 'row',
        alignItems: 'center',
        justifyContent: 'space-between'
    },

    // 搜索栏中的搜索框
    searchFrameStyle: {
        flexDirection: 'row',
        width: screenWidth * 0.8,
        height: 35,
        backgroundColor: '#f4f4f4',
        borderRadius: 2,
        marginLeft: 10,
        alignItems: 'center',
    },

    // 搜索框中的搜索图标
    searchImageStyle: {
        width: 15,
        height: 15,
        marginLeft: 8
    },

    textInputStyle: {
        width: screenWidth * 0.8 - 50,
        height: 40,
        marginLeft: 10
    },

    listViewStyle: {
        width: screenWidth,
    },
});